/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package services.Impl;

import java.util.Collection;
import java.util.Date;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import models.Messages;
import models.Users;
import services.interfaces.IMessageService;

/**
 *
 * @author SERGA
 */

@Stateless
@LocalBean
public class MessageServiceImpl extends GenericServiceImpl<Messages> implements IMessageService {

    @PersistenceContext(unitName="orsPU")
    private EntityManager em;
    
    
    public MessageServiceImpl() {
        super(Messages.class);
    }
    
    @Override
    protected EntityManager getEntityManager() {
        return this.em;
    }

    @Override
    public Collection<Messages> getMessageByIsRead(Boolean isRead) {
        Query q = em.createNamedQuery("Messages.findByIsRead").setParameter("isRead", isRead);
        Collection entities = q.getResultList();
        return entities;
    }

    @Override
    public Collection<Messages> getNewUserMessage(Users user) {
        Query q = em.createNamedQuery("Messages.findNewUserMessage").setParameter("users", user).setParameter("read", false);
        Collection entities = q.getResultList();
        return  entities;
    }

    @Override
    public void sendMessageToUser(Users from, Users to, String message) {
        Messages mess = new Messages();
        mess.setIdUserFrom(from);
        mess.setIdUserTo(to);
        mess.setText(message);
        mess.setDateTime(new Date());
        mess.setIsRead(Boolean.FALSE);
        this.create(mess);
    }

    @Override
    public Collection<Messages> getUsersDialog(Users to, Users from) {
        Query q = em.createNamedQuery("Messages.findUserDialog").setParameter("userTo", to).setParameter("userFrom", from);
        Collection entities = q.getResultList();
        return  entities;     
    }
    
}
